package com.xiaomi.eco.utils;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.*;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.RestTemplate;

import javax.annotation.PostConstruct;

@Configuration
@Slf4j
public class RequestUtils {



    private static RestTemplate restTemplate;

    @Autowired
    private static ObjectMapper objectMapper=new ObjectMapper();

//    @Bean
//    public RestTemplate restTemplate(RestTemplateBuilder builder) {
//        return builder.build();
//    }

    @PostConstruct
    public void init() {
        restTemplate = new RestTemplate();
    }

    public static String postFeiShuRequest(String tenantAccessToken,String requestUrl,String requestTask){
        //请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.set("Authorization","Bearer "+tenantAccessToken);

        //连接与超时设置
        HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();
        requestFactory.setConnectTimeout(1600000);
        requestFactory.setReadTimeout(1600000);
        restTemplate.setRequestFactory(requestFactory);

        //处理与请求
        HttpEntity<String> TaskEntity = new HttpEntity<>(requestTask, headers);
        String Taskresponse = restTemplate.postForObject(requestUrl, TaskEntity, String.class);
        System.out.println("Response: " + Taskresponse);
        return Taskresponse;
    }

    public static ResponseEntity<String>  exchangeFeiShuRequest(String tenantAccessToken,String requestUrl,String requestTask,HttpMethod requeststatus){
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.set("Authorization","Bearer "+tenantAccessToken);
        HttpEntity<String> TaskEntity = new HttpEntity<>(requestTask, headers); // 使用空字符串作为请求体，或者完全省略（取决于你的RestTemplate版本）
        ResponseEntity<String> deleteResponse = restTemplate.exchange(requestUrl, requeststatus, TaskEntity, String.class);
        System.out.println(deleteResponse);
        return deleteResponse;
    }
}
